﻿using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Departments
{
    public class FunctionalSystemTreeQueryHandler : IRequestHandler<FunctionalSystemTreeQueryCommand, Result>
    {
        private readonly IBaseRepository<FunctionalSystem> _functionalSystemRepository;

        public FunctionalSystemTreeQueryHandler(IBaseRepository<FunctionalSystem> functionalSystemRepository)
        {
            _functionalSystemRepository = functionalSystemRepository;
        }
        /// <summary>
        /// 智能体系树形
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(FunctionalSystemTreeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code=(int)CommonErrorCode.Search};
            try
            {
                var functionalSystem = await(await _functionalSystemRepository.GetAll()).Where(c=>c.PId==0).ToListAsync();
                List<Cascard> cascades = new List<Cascard>();
                foreach (var item in functionalSystem)
                {
                    Cascard cascard = new Cascard();
                    cascard.value = item.FunctionalSystemId;
                    cascard.label = item.FunctionalSystemName;
                    cascard.children =await GetCascards(item.FunctionalSystemId);
                    cascades.Add(cascard);
                }
                result.Data = cascades;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        public async Task<List<Cascard>> GetCascards(int pid = 0)
        {
            var functionalSystem = await (await _functionalSystemRepository.GetAll()).Where(c => c.PId == pid).ToListAsync();
            List<Cascard> cascades = new List<Cascard>();
            foreach (var item in functionalSystem)
            {
                Cascard cascard = new Cascard();
                cascard.value = item.FunctionalSystemId;
                cascard.label = item.FunctionalSystemName;
                cascard.children = await GetCascards(item.FunctionalSystemId);
                cascades.Add(cascard);
            }
            return cascades;
        }
    }
}
